package com.android.test.net;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Handler;

/*import com.yingyonghui.market.Constants;
import com.yingyonghui.market.json.JsonParams;
import com.yingyonghui.market.json.JsonUtils;
import com.yingyonghui.market.log.JsonLog;
import com.yingyonghui.market.model.Asset;
import com.yingyonghui.market.model.AssetDetail;
import com.yingyonghui.market.model.Category;
import com.yingyonghui.market.model.IconPair;
import com.yingyonghui.market.model.News;
import com.yingyonghui.market.model.NewsContent;
import com.yingyonghui.market.model.TestUser;
import com.yingyonghui.market.util.Base64;
import com.yingyonghui.market.util.DeviceUtil;
import com.yingyonghui.market.util.GlobalUtil;
import com.yingyonghui.market.util.IconCache;
import com.yingyonghui.market.util.NetworkUtil;*/


/* Class used to send Http request*/
public class HttpService {
 	private static final String TAG = HttpService.class.getSimpleName();
	private static HttpService httpService;
	private HttpManager httpManager;
	private Context mContext;
	public static String API = "lczm_api";
	protected final String mGetSnapshotURL = HttpManager.HOST_URI
			+ "download.jsp";
	protected final String mGetURL = "http://img.lczm.com/";   //Image URL
	protected final String mGetIconURL;

	// private DownloadService mDownloadService;

	private HttpService(Context context) {
		mContext = context;
		httpManager = HttpManager.getInstance(context);

		float density = mContext.getResources().getDisplayMetrics().density;
		if (density > 1) {
			mGetIconURL = mGetURL + "icon/72/";
		} else {
			mGetIconURL = mGetURL + "icon/48/";
		}
		return;
	}

	public static HttpService getInstance(Context context) {
		if (httpService == null) {
			httpService = new HttpService(context);
		}
		return httpService;
	}

	public void geOrgList(int category, int x, int y, int sortType,
			int id, Handler handler) {
/*		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getAppListParams(mContext, category,
				start, size, sortType);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addApiRequest(nameValuePairs, id, handler);*/
	}
/*
	public void getDownloadList(String[] installedPackages, int userId,
			int start, int size, int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getDownloadsParams(mContext,
				installedPackages, userId, start, size);

		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getUpdateAvailableNum(final String[] installedPackages,
			final int userId, int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getUpdateAvaliableNumParams(mContext,
				installedPackages, userId);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getTopAppDetailsList(int categoryId, int start, int size,
			int sortType, int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getBannerAndAppListParams(mContext,
				categoryId, start, size, sortType);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getNewsList(int start, int size, int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getNewsListParams(mContext, start,
				size);
		nameValuePairs.add(new BasicNameValuePair("param", params));
		if (nameValuePairs.size() == 5) {
			httpManager.addApiRequest(nameValuePairs, notifyId, handler);
		}

	}

	public void getNewsContent(final String newsUrl, int notifyId,
			Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams
				.getNewsContentParams(mContext, newsUrl);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getAppDetails(final int applicationId, int notifyId,
			Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getAppDetailParams(mContext,
				applicationId);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addApiRequest(nameValuePairs, notifyId, applicationId,
				handler);
	}

	public void getTestUser(int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getTestUserParams(mContext);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getAppRankingList(int categoryId, int periodType, int start,
			int size, int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getAppRankingListParams(mContext,
				categoryId, periodType, start, size);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getCategory(final int parentId, int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getAppCategoryParams(mContext,
				parentId);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getRecommendApp(int categoryId, int start, int size,
			int sortType, int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getRecommendAppParams(mContext,
				categoryId, start, size, sortType);
		nameValuePairs.add(new BasicNameValuePair("param", params));
		// Log.d(TAG, "getRecommendApp=====params: " + params);

		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getTopKeywords(int start, int size, int periodType,
			int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getTopKeywordsParams(mContext, start,
				size, periodType);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getSearchAppList(final String keywords, final int start,
			final int size, final int type, final String keywords2,
			int notifyId, Handler handler, int indexStart) {

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params;
		if (type == Constants.SEARCH_TYPE_BY_DEVELOPER) {
			params = JsonParams.getSearchByDeveloperParams(mContext, keywords,
					start, size, keywords2);
		} else if (type == Constants.SEARCH_TYPE_BY_PACKAGE) {
			params = JsonParams.getSearchByPkgnameParams(mContext, keywords,
					start, size, true);
		} else if (type == Constants.SEARCH_TYPE_BY_PACKAGE_EXTENDED) {
			params = JsonParams.getSearchByPkgnameParams(mContext, keywords,
					start, size, false);
		} else {
			params = JsonParams.getSearchByKeywordsParams(mContext, keywords,
					start, size, indexStart);
		}
		nameValuePairs.add(new BasicNameValuePair("param", params));
		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getAppCommentsList(final int applicationId, final int start,
			final int size, final String deviceId, int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getAppCommentsParams(mContext,
				applicationId, start, size);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getDeleteAppComment(final int commentId, final String deviceId,
			int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getDeleteCommentParams(mContext,
				commentId);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getReplyAppComment(final int parentId, final int applicationId,
			final String comment, final int rating, final boolean recursive,
			final String deviceId, int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String[] networkInfo = NetworkUtil.getNetWorkInfo(mContext);
		final String ipAddress = NetworkUtil.getLocalIpAddress();

		final String params = JsonParams.getSendCommentReplyParams(mContext,
				parentId, applicationId, comment, rating, networkInfo,
				ipAddress);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		// Log.d("HttpService", "getReplyAppComment=========params: " + params);
		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getAddAppComment(final int applicationId, final String comment,
			final int rating, final boolean recursive, final String deviceId,
			int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);
		final String[] networkInfo = NetworkUtil.getNetWorkInfo(mContext);
		final String ipAddress = NetworkUtil.getLocalIpAddress();
		final String params = JsonParams.getSendCommentParams(mContext,
				applicationId, comment, rating, networkInfo, ipAddress);

		nameValuePairs.add(new BasicNameValuePair("param", params));

		// Log.d("HttpService", "getAddAppComment=========params: " + params);
		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public String getReportError(int applicationId, int errorTypeId,
			long reportTime, String contactInfo, String feedbackInfo,
			long downloadStartTime, long downloadPendingTime,
			long downloadLastModifyTime, String downloadPercent, int notifyId,
			Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String sdkVersion = DeviceUtil.getSDKVersion();
		final String resolution = getResolution();
		final String hardware = getHardwareCode();
		final String deviceId = DeviceUtil.getIMEI(mContext);
		final float density = DeviceUtil.getScreenDensity(mContext);
		final int dpi = DeviceUtil.getScreenDensityDpi(mContext);

		String[] deviceInfo = new String[] { hardware, deviceId, resolution,
				sdkVersion, String.valueOf(density), String.valueOf(dpi) };
		String[] downloadInfo = new String[] {
				String.valueOf(downloadStartTime),
				String.valueOf(downloadPendingTime),
				String.valueOf(downloadLastModifyTime), downloadPercent };
		String[] networkInfo = NetworkUtil.getNetWorkInfo(mContext);

		final String params = JsonParams.getReportErrorParams(mContext,
				applicationId, errorTypeId, reportTime, contactInfo,
				feedbackInfo, downloadInfo, networkInfo, deviceInfo);

		// Log.d("HttpService", "getReportError=========params: " + params);
		nameValuePairs.add(new BasicNameValuePair("param", params));
		httpManager.addApiRequest(nameValuePairs, notifyId, handler);

		return params;
	}

	public void getAppRelativeList(final String pkgName, final int start,
			final int size, int notifyId, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getAppRelativeListParams(mContext,
				pkgName, start, size);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addApiRequest(nameValuePairs, notifyId, handler);
	}

	public void getAppScreenshortCount(int applicationId, int notifyId,
			Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getAppSnapsizeParams(mContext,
				applicationId);
		nameValuePairs.add(new BasicNameValuePair("param", params));
		httpManager.addApiRequest(nameValuePairs, notifyId, applicationId,
				handler);
	}

	public void getAppScreenshort(int position, int applicationId,
			int notifyId, Handler handler) {

		Rect rect = DeviceUtil.getScreenRect(mContext);
		String getURL = mGetSnapshotURL + "?";
		getURL = getURL + "type=snapshot";
		getURL = getURL + "&source=1";
		getURL = getURL + "&id=" + applicationId;
		getURL = getURL + "&full=0";
		getURL = getURL + "&resolution=" + rect.right + "x" + rect.bottom;
		getURL = getURL + "&no=";
		String url = getURL + position;
		// url = mGetIconURL + 13248 + ".png";
		getImage(url, notifyId, applicationId, handler);
	}

	public void getAppScreenshortFull(int position, int applicationId,
			int notifyId, Handler handler) {

		Rect rect = DeviceUtil.getScreenRect(mContext);
		String getURL = mGetSnapshotURL + "?";
		getURL = getURL + "type=snapshot";
		getURL = getURL + "&source=1";
		getURL = getURL + "&id=" + applicationId;
		getURL = getURL + "&full=1";
		getURL = getURL + "&resolution=" + rect.right + "x" + rect.bottom;
		getURL = getURL + "&no=";
		String url = getURL + position;
		// url = mGetIconURL + 13248 + ".png";
		getImage(url, notifyId, applicationId, handler);
	}

	//获取普通app列表的icon
	public void getAppIcon2(int notifyId, int applicationId, Handler handler) {
		SharedPreferences settings = mContext.getSharedPreferences("com.yingyonghui.market_preferences", 0);
		boolean displayIcons = settings.getBoolean("checkbox_display_icons", true);
		IconPair pair = IconCache.getInstance().get(applicationId);
		// WIFI 环境下加载图标，非WIFI环境下根据用户设置进行选择
		if (NetworkUtil.getNetwork(mContext).equals("WiFi")) {
			if (!pair.miss) {
				String getURL = mGetIconURL + applicationId + ".jpg";
				httpManager.addImageRequest(getURL, notifyId, applicationId,
						handler);
				pair.miss = true;
			}
		} else {
			if (displayIcons) {
				if (!pair.miss) {
					String getURL = mGetIconURL + applicationId + ".jpg";
					httpManager.addImageRequest(getURL, notifyId,
							applicationId, handler);
					pair.miss = true;
				}
			}
		}
	}

	//获取专栏列表的icon
	public void getImage(String url, int notifyId, Handler handler) {
		SharedPreferences settings = mContext.getSharedPreferences("com.yingyonghui.market_preferences", 0);
		boolean displayIcons = settings.getBoolean("checkbox_display_icons", true);
		
		IconPair pair = IconCache.getInstance().get(url);
		
		if (NetworkUtil.getNetwork(mContext).equals("WiFi")) {
			if (!pair.miss) {
				httpManager.addImageRequest(url, notifyId, handler);
				pair.miss = true;
			}			
		} else {
			if (displayIcons) {
				if (!pair.miss) {
					httpManager.addImageRequest(url, notifyId, handler);
					pair.miss = true;
				}
			}
		}
	}

	//获取其他图片：banner图，截图
	public void getImage(String url, int notifyId, int applicationId, Handler handler) {
		httpManager.addImageRequest(url, notifyId, applicationId, handler);
	}

	public void getInstalledLog(final String channel) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getInstallLogParams(mContext);
		nameValuePairs.add(new BasicNameValuePair("param", params));
		httpManager.addApiRequest(nameValuePairs);

		MobclickAgent.onEvent(mContext, "install_market_log", channel);
	}

	public void getUMengPromotionFeedback(String promotionId) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUmengUriParamater(nameValuePairs);

		final String params = JsonParams.getUMengPromotionFeedbackParams(
				mContext, promotionId);
		nameValuePairs.add(new BasicNameValuePair("param", params));
		httpManager.addApiRequest(nameValuePairs);
	}

	public void getYouyuPromotionFeedback(String promotionId,
			String promotionAgent, String from) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getYouyuPromotionFeedbackParams(
				mContext, promotionId, promotionAgent, from);
		nameValuePairs.add(new BasicNameValuePair("param", params));
		httpManager.addApiRequest(nameValuePairs);
	}

	public void getInstallUpdateLog(final String eventType,
			final String fromPage, final int category_id, final int type,
			final int periodType, final int appId, final String nickName) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String params = JsonParams.getInstallUpdateLogParams(mContext,
				eventType, fromPage, category_id, type, periodType, appId);
		nameValuePairs.add(new BasicNameValuePair("param", params));
		httpManager.addApiRequest(nameValuePairs);

		/*
		 * 添加umeng统计: 统计两种事件：update和download
		 * 属�?包括fromPage、applicationId、categoryId、rankingType、periodType
		 * fromPage:进入下载的页�? applicationId:下载的APP对应的Id
		 * categoryId:分类目录的编号，仅当fromPage为Category时有�?
		 * rankingType:按下�?评分/日期排行，仅当fromPage为Category时有�?
		 * periodType:按周/�?总排行，仅当fromPage为Ranking时有�?
		 */
    
    /*
		String data = fromPage;
		String sub = "";
		if (fromPage.equals("Category")) {
			if (nickName != null && nickName.length() >= 2) {
				data = nickName.substring(0, 2);
			}
			if (type != Constants.NAN) {
				switch (type) {
				case 0:
					sub = "download";
					break;
				case 1:
					sub = "rank";
					break;
				case 2:
					sub = "date";
					break;
				default:
					sub = "";
				}

				data = data + ":" + sub;
			}
		} else if (fromPage.equals("Ranking")) {
			if (periodType != Constants.NAN) {
				switch (periodType) {
				case 1:
					sub = "week";
					break;
				case 4:
					sub = "month";
					break;
				case 5:
					sub = "all";
					break;
				default:
					sub = "";
				}

				data = data + ":" + sub;
			}
		} else if (fromPage.equals("Preinstall")) {
			if (nickName != null && nickName.length() > 0) {
				data = nickName;
			}
		}

		if (eventType.equals("update")) {
			MobclickAgent.onEvent(mContext, "update_log", data);
		} else {
			MobclickAgent.onEvent(mContext, "install_log", data);
		}
	}

	public void postLog(byte[] data, String logName, Handler handler) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
		appendUriParamater(nameValuePairs);

		final String channel = GlobalUtil.getChannel(mContext);
		final long index = GlobalUtil.getBlockLogId(mContext, logName);

		final String params = JsonLog.getLogParams(Base64.encodeToString(data,
				false), channel, index);
		nameValuePairs.add(new BasicNameValuePair("param", params));

		httpManager.addLogRequest(nameValuePairs, data, logName, handler);
	}

	public ArrayList<Asset> getAssetObjectWithBannerFromJson(Context context,
			String json) {
		return JsonUtils.getAssetObjectWithBanner(context, json);
	}

	public ArrayList<Asset> getAssetFromJson(Context context, String json) {
		return JsonUtils.getAssetObjectWithBanner(context, json);
	}

	public ArrayList<Asset> getAppListFromJson(Context context, String json) {
		return JsonUtils.getAssetObject(context, json);
	}

	public ArrayList<Asset> getDownloadListFromJson(Context context, String json) {
		return JsonUtils.getAssetObject(context, json, false);
	}

	public ArrayList<News> getNewsListFromJson(String json) {
		return JsonUtils.getNewsListObject(json);
	}

	public NewsContent getNewsContentFromJson(String json) {
		return JsonUtils.getNewsContentObject(json);
	}

	public ArrayList<Category> getCategorysListFromJson(String json) {
		return JsonUtils.getCategoryObject(json);
	}

	public ArrayList<String> getTagListFromJson(String json) {
		return JsonUtils.getKeywordObject(json);
	}

	public ArrayList<Asset> getSearchListFromJson(Context context, String json) {
		return JsonUtils.getAssetObject(context, json, false);
	}

	public Object[] getSearchListForKeywordsFromJson(Context context,
			String json) {
		return JsonUtils.getAssetObjectForSearchKeywords(context, json, false);
	}

	public AssetDetail getAppDetailFromJson(Context context, String json) {
		return JsonUtils.getAssetDetailObject(context, json);
	}

	public TestUser getTestUserFromJson(String json) {
		return JsonUtils.getTestUserObject(mContext, json);
	}

	public Object[] getCommentsListFromJson(String json) {
		return JsonUtils.getCommentObject(json);
	}

	private void appendUriParamater(List<NameValuePair> nameValuePairs) {
		nameValuePairs.add(new BasicNameValuePair("key", ""));
		nameValuePairs.add(new BasicNameValuePair("referer", GlobalUtil
				.getUUIDString(mContext)));
		nameValuePairs.add(new BasicNameValuePair("api", API));
		nameValuePairs.add(new BasicNameValuePair("deviceId", DeviceUtil
				.getDeviceId(mContext)));
	}

	private void appendUmengUriParamater(List<NameValuePair> nameValuePairs) {
		nameValuePairs.add(new BasicNameValuePair("key", ""));
		nameValuePairs.add(new BasicNameValuePair("referer", GlobalUtil
				.getUUIDString(mContext)));
		nameValuePairs.add(new BasicNameValuePair("api", UMENG_API));
		nameValuePairs.add(new BasicNameValuePair("deviceId", DeviceUtil
				.getDeviceId(mContext)));
	}

	private String getResolution() {
		Rect rect = DeviceUtil.getScreenRect(mContext);
		return rect.right + "x" + rect.bottom;
	}

	private String getHardwareCode() {
		return DeviceUtil.getDeviceModel();
	}

	public void retryRequest(Integer id) {
		httpManager.retryRequest(id);
	}
	*/
}
